package xcf.data.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import xcf.data.model.Configuration;
import xcf.data.model.MapperStatement;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {

    private final Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element root = document.getRootElement();
        String namespace = root.attributeValue("namespace");
        List<Element> list = root.selectNodes("//select");
        list.forEach(v -> {
            String id = v.attributeValue("id");
            String returnType = v.attributeValue("returnType");
            String paramType = v.attributeValue("paramType");
            String sql = v.getTextTrim();
            MapperStatement statement = new MapperStatement();
            statement.setId(namespace + '.' + id)
                    .setParamTypeName(paramType)
                    .setReturnTypeName(returnType)
                    .setSqlSource(sql)
            ;
            configuration.getMapperStatementMap().put(statement.getId(), statement);
        });
    }
}
